package chapter8.eg10.program;

import chapter8.eg10.SubscribeReqProto;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.ArrayList;
import java.util.List;

public class TestSubscribeReqProto {

  private static byte[] encode(SubscribeReqProto.SubscribeReq req) {
    return req.toByteArray();
  }

  private static SubscribeReqProto.SubscribeReq decode(byte[] body)
    throws InvalidProtocolBufferException {
    return SubscribeReqProto.SubscribeReq.parseFrom(body);
  }

  private static SubscribeReqProto.SubscribeReq createSubscribeReq() {
    List<String> address = new ArrayList<>();
    address.add("NanJing YuHuaTai");
    address.add("BeiJing LiuLiChang");
    address.add("ShenZhen HongShuLin");

    SubscribeReqProto.SubscribeReq.Builder builder =
      SubscribeReqProto.SubscribeReq.newBuilder()
        .setSubReqID(1)
        .setUserName("Lilinfeng")
        .setProductName("Netty Book")
        .addAllAddress(address);
    return builder.build();
  }

  public static void main(String[] args) throws InvalidProtocolBufferException {
    SubscribeReqProto.SubscribeReq req = createSubscribeReq();
    System.out.println("Before encode: " + req.toString());
    SubscribeReqProto.SubscribeReq req2 = decode(encode(req));
    System.out.println("After encode: " + req.toString());
    System.out.println("Assert equal: --> " + req2.equals(req));
  }

}
